/// @tags:
#include <cstdio>
#include <cstring>
#include <functional>
#include <iostream>
#include <numeric>
#include <stack>

using std::cin, std::cout, std::endl;

namespace BlueQuantum {

constexpr int maxn = 2e5;

int value[5] = {1, 10, 100, 1000, 10000};
int sum[5];
char str[maxn + 5], suf[maxn + 5];

int main() {
  int t;
  cin >> t;
  while (t--) {
    cin >> (str + 1);
    int n = strlen(str + 1);
    std::fill(sum, sum + 5, 0);
    std::fill(suf, suf + n + 1, 'A');

    for (int i = n - 1; i >= 1; --i) {
      suf[i] = std::max(suf[i + 1], str[i + 1]);
    }
    suf[n] = 'A';
    int ans = 0;
    for (int i = 1; i <= n; ++i) {
      if (suf[i] > str[i]) {
        ans -= value[str[i] - 'A'];
      } else {
        ans += value[str[i] - 'A'];
      }
    }
    int maxans = ans;

    std::vector<int> stk;
    for (int i = 1; i <= n; ++i) {
      if (suf[i] > str[i]) {
        maxans = std::max(maxans, ans + value[str[i] - 'A'] - 1);
        maxans =
            std::max(maxans, ans + value[suf[i] - 'A'] + value[str[i] - 'A']);
        for (int j = suf[i] - 'A' + 1; j < 5; ++j) {
          int tmp = 0;
          for (int k = suf[i] - 'A'; k < j; ++k) {
            tmp += sum[k] * value[k];
          }
          maxans =
              std::max(maxans, ans - tmp * 2 + value[j] + value[str[i] - 'A']);
        }
      } else {
        for (int j = str[i] - 'A' + 1; j < 5; ++j) {
          int tmp = 0;
          for (int k = str[i] - 'A'; k < j; ++k) {
            tmp += sum[k] * value[k];
          }
          maxans =
              std::max(maxans, ans - tmp * 2 + value[j] - value[str[i] - 'A']);
        }
        for (int j = suf[i] - 'A'; j < str[i] - 'A'; ++j) {
          int tmp = 0;
          for (int k = j; k < str[i] - 'A'; ++k) {
            tmp += sum[k] * value[k];
          }
          maxans =
              std::max(maxans, ans + tmp * 2 + value[j] - value[str[i] - 'A']);
        }
      }

      while (!stk.empty() && str[stk.back()] < str[i]) {
        sum[str[stk.back()] - 'A']--;
        stk.pop_back();
      }
      stk.push_back(i);
      sum[str[i] - 'A']++;
    }
    cout << maxans << '\n';
  }
  return 0;
}

}  // namespace BlueQuantum

int main() {
#ifndef ONLINE_JUDGE
#ifdef LOCAL
  freopen("/tmp/CodeTmp/testdata.in", "r", stdin);
  freopen("/tmp/CodeTmp/testdata.out", "w", stdout);
#else
  freopen("C. Ranom Numbers.in", "r", stdin);
  freopen("C. Ranom Numbers.out", "w", stdout);
#endif
#endif

  std::ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
  return BlueQuantum::main();
}
